﻿@inherits AdminCompontentBase
<SSimpleModal Value="@_visible" Title="@T("ChartPreview")" SaveText="@T("UpdateChart")" Width="Width" HeaderClass="py-2" BodyClass="pt-0" OnCancel="()=>_visible=false">
    <AlarmPreviewChart AlarmRule="_alarmRule" ChartYAxisUnit="@AlarmRule.ChartYAxisUnit"></AlarmPreviewChart>
    @if (AlarmRule.Type == AlarmRuleTypes.Log)
    {
        <DefaultTitle>
            @T("LogSamplingPreview")
            <DefaultTooltip Class="ml-2 mt-n1" Tooltip="@T("LogSamplingPreviewTips")" />
        </DefaultTitle>
        <JsonPre @bind-Value="@_logStr" Class="rounded-2 emphasis"></JsonPre>
    }
</SSimpleModal>

@code {
    [Parameter]
    public StringNumber Width { get; set; } = 770;

    [EditorRequired]
    [Parameter]
    public AlarmRuleUpsertViewModel AlarmRule { get; set; } = new();

    [Inject]
    public ITscClient TscClient { get; set; } = default!;

    private AlarmRuleUpsertViewModel _alarmRule = new();

    protected override string? PageName { get; set; } = "AlarmChartBlock";

    private bool _visible = false;

    private LogDto _log = new();
    private string _logStr = string.Empty;

    public async Task OpenModalAsync()
    {
        _alarmRule = AlarmRule;
        await GetLatestAsync();
        await InvokeAsync(() =>
        {
            _visible = true;
            StateHasChanged();
        });
    }

    public async Task GetLatestAsync()
    {
        var request = new LogLatestRequest
            {
                Start = DateTime.Now.AddDays(-20),
                End = DateTime.Now,
                IsDesc = true
            };

        try
        {
            var log = await TscClient.LogService.GetLatestAsync(request);
            _logStr = JsonSerializer.Serialize(log);
        }
        catch (Exception)
        {
            _logStr = "{}";
        }
    }
}
